﻿using System;
using System.Collections.Concurrent;
using System.Net;
using Grundy.Common;
using Grundy.Entity;
using System.Linq;
using Grundy.Message;

namespace Grundy.Licensing.Server
{
    public class LicenseData
    {
        private ILicensingStrategy _licensingStrategy;
        private object _syncLock = new object();

        public LicenseData(CustomerLicenseEntitlement cple, LicensingStrategyFactory licensingStrategyFactory)
        {
            CustomerLicenseEntitlement = cple;
            Key = cple.ToFeatureIdentificationKey();
            _licensingStrategy = licensingStrategyFactory.GetLicensingStrategyForLicense(cple.License, new LicenseEntitlementValidity(cple), Key);
        }

        public FeatureIdentificationKey Key { get; private set; }
        public CustomerLicenseEntitlement CustomerLicenseEntitlement { get; private set; }

        public bool Reassert(Guid clientSessionId, EndPoint endpoint)
        {
            return _licensingStrategy.Reassert(clientSessionId, endpoint);
        }

        public void CleanupClientSessions()
        {
            lock (_syncLock)
            {
                _licensingStrategy.Cleanup();
            }
        }

        public virtual Guid Checkout(LicenseRequestInformation lri)
        {
            return _licensingStrategy.Checkout(lri, _syncLock);
        }

        public bool HasClientSession(Guid sessionId)
        {
            return _licensingStrategy.HasClientSession(sessionId);
        }

        public bool Checkin(LicenseRequestInformation lri)
        {
            return _licensingStrategy.Checkin(lri, _syncLock);
        }

        public long GetExhaustedLicenseCount()
        {
            return _licensingStrategy.GetExhaustedLicenseCount();
        }
    }
}